import { DescItem } from '@/components/Description/index';
import { componentMap } from '@/components/view/componentMap';
import { h } from 'vue';
import { isArray, isFunction } from './is';
import { RenderCallbackParams, FormSchema } from '@/components/Form';

/**
 * 将表单元数据转成详情元数据
 * @param formSchemas
 * @returns
 */
export const formToDescription = (formSchemas: FormSchema[], formModel: any): Array<DescItem> => {
  // console.log('formModel', formModel);
  const group: Array<DescItem> = [];
  if (!isArray(formSchemas)) return group;
  for (let i = 0; i < formSchemas.length; i++) {
    const item = formSchemas[i];
    // 找到分割线
    if ((item as any).component === 'Divider') {
      group.push({
        field: item.field,
        label: item.label,
        children: [],
      } as DescItem);
      // 将分割线后面的数据添加到group中
      for (let j = i + 1; j < formSchemas.length; j++) {
        const nextItem = formSchemas[j];
        // 找到下面的分割线
        if ((nextItem as any).component === 'Divider') {
          // 中断
          i = j - 1;
          break;
        } else {
          if (
            isDescription({
              schema: nextItem,
              values: formModel,
              model: formModel,
              field: item.field,
            })
          ) {
            group[group.length - 1].children?.push({
              field: nextItem.field,
              label: nextItem.label,
              span: nextItem.colProps?.span || 24,
              render: renderFun(nextItem, formModel),
            } as DescItem);
          }
        }
      }
    }
  }
  if (group.length > 0) {
    return group;
  }
  return [
    {
      field: 'baseinfo',
      label: '基本信息',
      children: formSchemas
        .filter((item) => {
          return isDescription({
            schema: item,
            values: formModel,
            model: formModel,
            field: item.field,
          });
        })
        .map((item) => {
          return {
            field: item.field,
            label: item.label,
            span: item.colProps?.span || 24,
            render: renderFun(item, formModel),
          } as DescItem;
        }),
    },
  ];
};
export const isDescription = (renderCallbackParams: RenderCallbackParams): boolean => {
  const schema = renderCallbackParams.schema;
  if (isFunction(schema.description)) {
    return schema.description(renderCallbackParams);
  }
  return schema.description !== false;
};

const renderFun = (item, formModel) => {
  const ViewComponent = componentMap.get((item as any).component);
  let render: any = undefined;
  if (ViewComponent) {
    let componentProps = item.componentProps;
    render = (value) => {
      if (typeof componentProps == 'function') {
        componentProps = componentProps({
          formModel,
          schema: item,
        });
      }
      return h(ViewComponent, {
        // data: data,
        value: value,
        ...componentProps,
      });
    };
  }
  return render;
};
/**
 * 表单字段通过ifShow
 * @param data
 * @param ext
 * @returns
 */
export const ifShow = (data, ext) => {
  const isUpdate = data?.values?.id;
  if (isUpdate && ext?.editHide == 1) {
    // 如果是编辑，且隐藏，则不显示
    return false;
  }
  if (!isUpdate && ext?.addHide == 1) {
    // 如果是新增，且隐藏，则不显示
    return false;
  }
  return _handleControlled(data, ext);
};
/**
 * 通用处理规则
 * @param data
 * @param ext
 * @returns
 */
export const _handleControlled = (data, ext) => {
  const controlledFieldName = ext?.controlledFieldName;
  const controlledFieldValue = ext?.controlledFieldValue;
  if (controlledFieldName && controlledFieldValue) {
    return controlledFieldValue
      .split(',')
      .includes(data?.values?.[controlledFieldName]?.toString());
  }
  return true;
};
/**
 * 详情字段通过ifShow
 * @param data
 * @param ext
 * @returns
 */
export const ifDescription = (data, ext) => {
  if (ext?.viewHide == 1) {
    // 如果是详情，且隐藏，则不显示
    return false;
  }
  return _handleControlled(data, ext);
};
